package com.young.ysepay.service.impl;

import com.alibaba.fastjson.JSON;
import com.young.ysepay.domain.YsRoutingReceiptDO;
import com.young.ysepay.dto.YsPayDTO;
import com.young.ysepay.service.*;
import com.young.ysepay.utils.DateFormatHelper;
import com.young.ysepay.utils.Https;
import com.young.ysepay.utils.JSONUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;


/**
 * @Author: WANGNING
 * @Email wyn20140226@aliyun.com
 * @Date: 2019/6/4 18:15
 * @Des 银盛分账接口处理
 */
@Service
public class YsSplitServiceImpl implements YsSplitService {

    public static final Logger logger = LoggerFactory.getLogger(YsSplitServiceImpl.class);

    @Autowired
    private YsBusinessPramService ysBusinessPramService;
    @Autowired
    private YsBuildRequestParaService ysBuildRequestParaService;
    @Autowired
    private YsVerifyJsonSignService ysVerifyJsonSignService;
    @Autowired
    private YsRoutingReceiptService ysRoutingReceiptService;

    @Override
    public String splitReceipt(Map<String, Object> mapParams) {
        logger.info("----------begin 开始调用银盛分账----------");
        logger.info("接收优店参数请求银盛分账"+JSONUtils.objectToJson(mapParams));

        //获取原交易单号
        Object temp = mapParams.get("biz_content");
        String bizContent = temp != null ? temp.toString() : null;
        Map<String, Object> jsonMap = JSONUtils.jsonToMap(bizContent);
        temp = jsonMap.get("out_trade_no");
        String out_trade_no = temp != null ? temp.toString() : null;
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String str = "";
        //获取配置数据
        YsPayDTO ysPayDTO = ysBusinessPramService.ysBusinessPram();

        //封装公共参数
        Map<String, String> param = new HashMap<>();
        param.put("method", "ysepay.single.division.online.accept");
        param.put("partner_id", ysPayDTO.getPARTNER_ID());
        param.put("timestamp", DateFormatHelper.getNowTimeStr());
        param.put("charset", ysPayDTO.getDEFAULT_CHARSET());
        param.put("sign_type", ysPayDTO.getSIGN_ALGORITHM());
        param.put("version", ysPayDTO.getVERSION());
        param.put("notify_url", ysPayDTO.getNOTIFY_FZ_URL());
        param.put("biz_content", bizContent);

        try {
            //签名
            logger.info("银盛中心业务及配置参数封装"+JSONUtils.objectToJson(param));
            Map<String, String> sPara = ysBuildRequestParaService.buildRequestPara(param);
            logger.info("银盛分账请求接口参数：" + JSONUtils.objectToJson(sPara));
            String returnString = Https.httpsSend(ysPayDTO.getYSEPAY_GATEWAY_URL_DSF(), sPara);
            logger.info("银盛分账请求接口参数返回数据：" + JSONUtils.objectToJson(returnString));
            resultMap = (Map) JSON.parse(returnString);
            Object obj = resultMap.get("ysepay_single_division_online_accept_response");
            boolean verifyResult = false;

            if (obj == null) {
                return JSONUtils.objectToJson("银盛返回结果为空");
            }
                int ss = returnString.indexOf("ysepay_single_division_online_accept_response");
                str = returnString.substring(ss);
                str = str.replace("ysepay_single_division_online_accept_response", "");
                str = str.substring(2, str.length() - 1);
                verifyResult = ysVerifyJsonSignService.verifyJsonSign(resultMap.get("sign").toString(), str, "utf-8");
                logger.error("分账请求回执信息:{},验签是否成功:{}",str,verifyResult);
                if (null == str || str.equals("")) {
                    return JSONUtils.objectToJson("银盛返回结果为空");
                }
                //分账同步请求记录保存
                this.savaSplitSync(str,out_trade_no);

        } catch (Exception e) {
            logger.error("分帐请求失败-----" + e.getMessage());
            e.printStackTrace();
        }finally {
            logger.info("订单号:{},优店调用银盛分账同步回执结果:{}",out_trade_no,str);
            return str;
        }
    }



    //银盛分账请求同步日志记录保存
    private void savaSplitSync(String str,String out_trade_no) {
        YsRoutingReceiptDO ysRoutingReceiptDO = new YsRoutingReceiptDO();
        logger.error("银盛分账请求同步保存信息参数" + JSONUtils.jsonToMap(str));
        Map<String, Object> map = JSONUtils.jsonToMap(str);
        String code = map.get("code").toString();
        try {
            if (code.equals("10000")) {
                String retrunInfo = map.get("retrunInfo").toString();
                ysRoutingReceiptDO.setOutTradeNo(out_trade_no);
                ysRoutingReceiptDO.setGmtCreate(new Date());
                ysRoutingReceiptDO.setGmtModified(new Date());
                ysRoutingReceiptDO.setIsDelete("1");
                ysRoutingReceiptDO.setResponseType("1");
                ysRoutingReceiptDO.setDivisionStatus(retrunInfo);
                ysRoutingReceiptDO.setDivisionStatusCode(code);
                ysRoutingReceiptService.save(ysRoutingReceiptDO);
            } else {
                String sub_msg = map.get("sub_msg").toString();
                ysRoutingReceiptDO.setGmtCreate(new Date());
                ysRoutingReceiptDO.setGmtModified(new Date());
                ysRoutingReceiptDO.setResponseType("1");
                ysRoutingReceiptDO.setIsDelete("1");
                ysRoutingReceiptDO.setDivisionStatusCode(code);
                ysRoutingReceiptDO.setNote(sub_msg);
                ysRoutingReceiptDO.setOutTradeNo(out_trade_no);
                ysRoutingReceiptDO.setDivisionStatus("分账受理失败");
                ysRoutingReceiptService.save(ysRoutingReceiptDO);
            }
        } catch (Exception e) {
            logger.error("银盛分账同步回执保存信息失败"+ysRoutingReceiptDO.toString());
            e.printStackTrace();

        }
    }
}